package com.dreamsail.config;

import com.dreamsail.util.SSLUtils;
import lombok.Data;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

import javax.net.ssl.SSLSocketFactory;

/**
 * @Description MqttConfiguration
 * @Date 2023/2/27
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "mqtt")
public class MqttConfiguration {
    public static final Logger log = LoggerFactory.getLogger(MqttConfiguration.class);
    private String username;
    private String password;
    private String url;
    private String clientId;
    private String topic = "TOPIC_DEFAULT";
    private String outTopic = "TOPIC_DEFAULT";
    private Integer completionTimeout = 5000;
    private boolean sslEnabled = false;
    private String sslCaCertPath;
    private String sslClientCertPath;
    private String sslClientKeyPath;
    private String sslKeyPassword;

    /**
     * 注册MQTT客户端工厂
     *
     * @return
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        log.info("MqttConfiguration.mqttClientFactory.url>>>{}", url);
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();

        // 设置连接参数
        options.setCleanSession(true);
        options.setConnectionTimeout(30); // 30秒连接超时
        options.setKeepAliveInterval(60); // 60秒心跳间隔
        options.setAutomaticReconnect(true);
        options.setUserName(this.getUsername());
        options.setPassword(this.getPassword().toCharArray());
        options.setServerURIs(new String[]{this.getUrl()});

        // 如果启用了SSL且URL是SSL协议，则配置SSL SocketFactory
        if (sslEnabled && url != null && url.startsWith("ssl://")) {
            try {
                log.info("Configuring SSL for MQTT connection...");
                SSLSocketFactory socketFactory = SSLUtils.getSocketFactory(sslCaCertPath, sslClientCertPath, sslClientKeyPath, "");
                options.setSocketFactory(socketFactory);
                log.info("SSL SocketFactory configured successfully");
            } catch (Exception e) {
                log.error("Failed to configure SSL SocketFactory, falling back to non-SSL connection", e);
                // SSL配置失败时，不设置SocketFactory，继续使用普通连接
            }
        } else {
            log.info("SSL not enabled or URL not SSL type, using regular connection");
        }

        factory.setConnectionOptions(options);
        return factory;
    }
}
